package jdbc02;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class MyJdbcConnection {

	public static void main(String[] args) {

		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		try {
			Class.forName(getProperty("jdbc.driver"));

			String url = getProperty("url");
			String user = getProperty("user");
			String password = getProperty("password");

			conn = DriverManager.getConnection(url, user, password);
			System.out.println("get connection: " + conn);

			stmt = conn.createStatement();
			rs = stmt.executeQuery("select * from besuper.player");
			
			while (rs.next()) {
				int id = rs.getInt("id");
				String name = rs.getString("name");
				int score = rs.getInt("score");
				String username = rs.getString("username");
				
				System.out.println("id: " + id
						+ ", name: " + name
						+ ", score: " + score
						+ ", username: " + username);
			}

		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if (conn != null) {
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private static String getProperty(String key) {
		Properties props = new Properties();
		try {
			props.load(new FileInputStream("conn.properties"));

			return props.getProperty(key);

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

}
